import gzip

import matplotlib.pyplot as plt
import numpy as np

# 定义MNIST文件对应的路径
MNIST_FILE_PATH = 'D:/TT_WORK+/PyCharm/20250109_1_CNN/MNIST/'


def load_data():
    # 加载图像数据
    with gzip.open(MNIST_FILE_PATH + 'train-images-idx3-ubyte.gz', 'rb') as f:  # 训练集
        X_train = np.frombuffer(f.read(), dtype=np.uint8, offset=16).reshape(-1, 28 * 28)

    with gzip.open(MNIST_FILE_PATH + 't10k-images-idx3-ubyte.gz', 'rb') as f:  # 测试集标签
        X_test = np.frombuffer(f.read(), dtype=np.uint8, offset=16).reshape(-1, 28 * 28)

    # 加载标签数据
    with gzip.open(MNIST_FILE_PATH + 'train-labels-idx1-ubyte.gz', 'rb') as f:  # 训练集标签
        y_train = np.frombuffer(f.read(), dtype=np.uint8, offset=8)

    with gzip.open(MNIST_FILE_PATH + 't10k-labels-idx1-ubyte.gz', 'rb') as f:  # 测试集标签
        y_test = np.frombuffer(f.read(), dtype=np.uint8, offset=8)

    return (X_train, y_train), (X_test, y_test)


# 加载MNIST数据集
(X_train, y_train), (X_test, y_test) = load_data()

# 选择要显示的图像的索引
indices = [0, 1, 2, 3, 4]  # 显示前5张图片

# 设置画布和子图的尺寸
plt.figure(figsize=(10, 3))

for i, index in enumerate(indices):
    # 每个子图显示一张图片
    plt.subplot(1, len(indices), i + 1)  # 参数1, len(indices), i+1 分别表示：行数, 列数, 当前子图编号
    plt.imshow(X_train[index].reshape(28, 28), cmap='gray')  # 将图像数据重塑为28x28，并使用灰度色图显示
    plt.title('Label: ' + str(y_train[index]))  # 显示图像对应的标签
    plt.axis('off')  # 不显示坐标轴

# 调整子图间距
plt.subplots_adjust(hspace=0.5)

# 显示整个画布
plt.show()
